"""
霓虹粒子特效模块 - 赛博朋克风格的动态粒子效果
"""

import math
import random
from PySide2.QtCore import QTimer, Qt, QPointF
from PySide2.QtGui import QPainter, QColor, QRadialGradient, QBrush
from PySide2.QtWidgets import QWidget


class NeonParticle:
    """霓虹粒子类"""
    
    def __init__(self, width, height, speed_multiplier=1.0):
        # 位置和运动
        self.x = random.uniform(0, width)
        self.y = random.uniform(0, height)
        self.vx = random.uniform(-2, 2) * speed_multiplier
        self.vy = random.uniform(-2, 2) * speed_multiplier
        
        # 粒子属性
        self.size = random.uniform(2, 8)
        self.max_size = self.size * random.uniform(1.5, 3.0)
        self.min_size = self.size * 0.3
        
        # 霓虹颜色 - 蓝色系主题
        colors = [
            QColor(0, 100, 255),    # 亮蓝色
            QColor(0, 150, 255),    # 天蓝色
            QColor(0, 200, 255),    # 浅蓝色
            QColor(100, 150, 255),  # 蓝紫色
            QColor(0, 180, 255),    # 青蓝色
            QColor(50, 120, 255),   # 深蓝色
        ]
        self.color = random.choice(colors)
        
        # 闪烁效果
        self.pulse_phase = random.uniform(0, 2 * math.pi)
        self.pulse_speed = random.uniform(0.05, 0.15)
        self.brightness = random.uniform(0.3, 1.0)
        self.base_brightness = self.brightness
        
        # 光晕效果
        self.glow_multiplier = random.uniform(2.0, 4.0)
        
        # 生命周期
        self.life = 1.0
        self.life_decay = random.uniform(0.001, 0.003)
        
        # 边界
        self.width = width
        self.height = height
        
    def update(self):
        """更新粒子状态"""
        # 移动
        self.x += self.vx
        self.y += self.vy
        
        # 边界反弹
        if self.x <= 0 or self.x >= self.width:
            self.vx *= -0.8
            self.x = max(0, min(self.width, self.x))
        if self.y <= 0 or self.y >= self.height:
            self.vy *= -0.8
            self.y = max(0, min(self.height, self.y))
        
        # 脉冲效果
        self.pulse_phase += self.pulse_speed
        pulse = math.sin(self.pulse_phase) * 0.5 + 0.5
        self.brightness = self.base_brightness * (0.5 + pulse * 0.5)
        self.size = self.min_size + (self.max_size - self.min_size) * pulse
        
        # 生命周期
        self.life -= self.life_decay
        if self.life <= 0:
            self.respawn()
    
    def respawn(self):
        """重生粒子"""
        self.x = random.uniform(0, self.width)
        self.y = random.uniform(0, self.height)
        self.life = 1.0
        self.brightness = random.uniform(0.3, 1.0)
        self.base_brightness = self.brightness


class NeonParticleEffect(QWidget):
    """霓虹粒子特效组件"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAttribute(Qt.WA_TransparentForMouseEvents)
        self.setWindowFlags(Qt.FramelessWindowHint)
        
        # 特效设置
        self.enabled = True
        self.particle_density = 'medium'  # low, medium, high
        self.animation_speed = 'normal'   # slow, normal, fast
        
        # 粒子列表
        self.particles = []
        
        # 动画定时器
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_animation)
        self.timer.start(16)  # 约60FPS
        
        # 初始化粒子
        self.init_particles()
    
    def get_particle_count(self):
        """根据密度设置获取粒子数量"""
        if not self.parent():
            return 50
            
        area = self.parent().width() * self.parent().height()
        base_count = area // 10000  # 基础密度
        
        if self.particle_density == 'low':
            return max(20, base_count // 2)
        elif self.particle_density == 'medium':
            return max(50, base_count)
        elif self.particle_density == 'high':
            return max(100, base_count * 2)
        return 50
    
    def get_speed_multiplier(self):
        """根据动画速度设置获取速度倍数"""
        if self.animation_speed == 'slow':
            return 0.5
        elif self.animation_speed == 'normal':
            return 1.0
        elif self.animation_speed == 'fast':
            return 2.0
        return 1.0
    
    def init_particles(self):
        """初始化粒子"""
        if not self.parent():
            return
            
        self.particles.clear()
        particle_count = self.get_particle_count()
        speed_multiplier = self.get_speed_multiplier()
        
        width = self.parent().width()
        height = self.parent().height()
        
        for _ in range(particle_count):
            particle = NeonParticle(width, height, speed_multiplier)
            self.particles.append(particle)
    
    def set_enabled(self, enabled):
        """设置特效开关"""
        self.enabled = enabled
        if enabled:
            self.timer.start(16)
            self.show()
        else:
            self.timer.stop()
            self.hide()
    
    def set_particle_density(self, density):
        """设置粒子密度"""
        if density in ['low', 'medium', 'high']:
            self.particle_density = density
            self.init_particles()
    
    def set_animation_speed(self, speed):
        """设置动画速度"""
        if speed in ['slow', 'normal', 'fast']:
            self.animation_speed = speed
            speed_multiplier = self.get_speed_multiplier()
            for particle in self.particles:
                particle.vx *= speed_multiplier
                particle.vy *= speed_multiplier
    
    def update_animation(self):
        """更新动画"""
        if not self.enabled:
            return
            
        for particle in self.particles:
            particle.update()
        
        self.update()  # 触发重绘
    
    def resizeEvent(self, event):
        """窗口大小改变事件"""
        super().resizeEvent(event)
        if self.parent():
            self.resize(self.parent().size())
            # 更新粒子边界
            for particle in self.particles:
                particle.width = self.width()
                particle.height = self.height()
    
    def paintEvent(self, event):
        """绘制霓虹粒子特效"""
        if not self.enabled or not self.particles:
            return
            
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setRenderHint(QPainter.SmoothPixmapTransform)
        
        for particle in self.particles:
            self.draw_particle(painter, particle)
    
    def draw_particle(self, painter, particle):
        """绘制单个霓虹粒子"""
        painter.save()
        
        # 外层光晕 - 霓虹效果
        glow_size = particle.size * particle.glow_multiplier
        glow = QRadialGradient(particle.x, particle.y, glow_size)
        
        color = particle.color
        alpha = int(particle.brightness * particle.life * 255)
        
        # 霓虹光晕渐变
        glow.setColorAt(0, QColor(color.red(), color.green(), color.blue(), alpha))
        glow.setColorAt(0.3, QColor(color.red(), color.green(), color.blue(), alpha // 2))
        glow.setColorAt(0.7, QColor(color.red(), color.green(), color.blue(), alpha // 4))
        glow.setColorAt(1, QColor(color.red(), color.green(), color.blue(), 0))
        
        painter.setBrush(QBrush(glow))
        painter.setPen(Qt.NoPen)
        painter.drawEllipse(int(particle.x - glow_size), int(particle.y - glow_size),
                          int(glow_size * 2), int(glow_size * 2))
        
        # 内核 - 亮白色核心
        core_size = particle.size * 0.3
        core = QRadialGradient(particle.x, particle.y, core_size)
        core.setColorAt(0, QColor(255, 255, 255, alpha))
        core.setColorAt(0.5, QColor(color.red(), color.green(), color.blue(), alpha))
        core.setColorAt(1, QColor(color.red(), color.green(), color.blue(), 0))
        
        painter.setBrush(QBrush(core))
        painter.drawEllipse(int(particle.x - core_size), int(particle.y - core_size),
                          int(core_size * 2), int(core_size * 2))
        
        painter.restore()
